import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/'
import Account from '@/components/account/Account'
import Product from '@/components/product/Product'
import Login from '@/components/login/Login'

Vue.use(Router)

// export default new Router({
const router = new Router({
  routes: [
    {
      path: '/product',
      name: 'Product',
      component: Product,
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/account',
      name: 'Account',
      component: Account,
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/',
      name: 'Login',
      component: Login
    }
  ]
})

router.beforeEach((to, from, next) => {
  var token = sessionStorage.getItem('supplier')
  if (store.state.token !== '' && store.state.isLogin) {
    if (to.meta.requireAuth) {
      next()
    } else {
      next({path: '/'})
    }
  } else {
    if (to.meta.requireAuth) {
      if (token === null) {
        next({path: '/'})
      } else {
        store.dispatch('setToken', token)
        store.dispatch('setLogin', 1)
        next()
      }
    } else {
      next()
    }
  }
})

export default router
